<?php

namespace yunj\command;

use think\console\Input;
use think\console\Output;
use think\facade\Db;
use yunj\app\admin\service\route\RouteFileService;
use yunj\app\admin\service\route\RouteRequestService;
use yunj\core\Command as BaseCommand;
use yunj\app\admin\service\route\RouteSyncSystemDataService;

class AdminReset extends BaseCommand {

    protected function configure() {
        $this->setName('yunj:admin-reset')
            ->setDescription('云静超管账户重置');
    }

    protected function execute(Input $input, Output $output) {
        ini_set("display_errors", "On");//打开错误提示
        ini_set("error_reporting", E_ALL);//显示所有错误
        set_time_limit(3600);

        try {
            $username = $this->ask('请输入管理员账户名[字母/数字/下划线_/短横线-]（留空随机生成）');
            if (!$username) $username = rand_char(5);
            if (!preg_match("/^[A-Za-z0-9\_\-]+$/", $username)) {
                $this->warning('管理员账户名仅支持[字母/数字/下划线_/短横线-]组合');
                return;
            }
            $password = $this->ask('请输入管理员账户密码[字母/数字/下划线_/短横线-]（留空随机生成）');
            if (!$password) $password = rand_char(8);
            if (!preg_match("/^[A-Za-z0-9\_\-]+$/", $password)) {
                $this->warning('管理员账户密码仅支持[字母/数字/下划线_/短横线-]组合');
                return;
            }
            // 重置账户密码
            [$passwordHash, $passwordSalt] = password_handle($password);
            $res = Db::name('admin_member')->update([
                'id' => 1,
                'username' => $username,
                'password_hash' => $passwordHash,
                'password_salt' => $passwordSalt,
                'last_update_time' => time()
            ]);
            if (!$res) {
                throw new \RuntimeException('超管账户重置失败');
            }
            // 输出新的账户密码
            $this->success('超管账户重置成功，新帐户密码如下：', true);
            $this->info("账户：{$username}");
            $this->info("密码：{$password}");
        } catch (\Throwable $e) {
            $this->error(exception_to_str($e));
        }
    }
}